<template>
	<el-dialog :visible.sync="dialogVisible" :title="title" :close-on-click-modal="false" width="750px" @close="close">
		<!--  html  -->
		<el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-suffix="：" label-width="120px" size="small">
			<el-form-item label="券名称">{{ form.couponName }}</el-form-item>
			<div v-if="(editType === 'maxCoupons' || editType === 'maxCouponsByDay') && ['cash', 'discount', 'exchange'].includes(form.couponType)">
				<!-- 发放预算 -->
				<el-form-item label="发放预算">
					<el-form-item v-if="editType === 'maxCoupons'" prop="maxCoupons">
						<el-checkbox v-model="form.maxCouponsChecked">设置有效期内可发放总上限为&nbsp;</el-checkbox>
						<el-input v-model="form.maxCoupons" :disabled="!form.maxCouponsChecked" placeholder="请输入" maxlength="10" class="w-200">
							<template slot="append">
								次
							</template>
						</el-input>
					</el-form-item>
					<el-form-item v-if="editType === 'maxCouponsByDay'" prop="maxCouponsByDay">
						<el-checkbox v-model="form.maxCouponsByDayChecked">设置一个自然日可发放上限为&nbsp;</el-checkbox>
						<el-input v-model="form.maxCouponsByDay" :disabled="!form.maxCouponsByDayChecked" placeholder="请输入" maxlength="10" class="w-200">
							<template slot="append">
								次
							</template>
						</el-input>
					</el-form-item>
				</el-form-item>
			</div>
			<div v-if="(editType === 'maxCoupons' || editType === 'maxCouponsByDay') && ['cash_wx_busi', 'discount_wx_busi', 'cash_wx_pay'].includes(form.couponType)">
				<!-- 预算 -->
				<el-form-item label="发放预算" class="is-required">
					<el-form-item v-if="editType === 'maxCoupons'" prop="maxCoupons">
						<span>批次总预算次数：&#12288;</span>
						<el-input v-model="form.maxCoupons" placeholder="请输入" maxlength="8" class="w-200">
							<template slot="append">
								次
							</template>
						</el-input>
						<span>&nbsp;5 ≤ 次数 ≤ 10000000</span>
					</el-form-item>
					<el-form-item v-if="editType === 'maxCouponsByDay'" prop="maxCouponsByDay">
						<span>单天发放上限次数：</span>
						<el-input v-model="form.maxCouponsByDay" placeholder="请输入" maxlength="8" class="w-200">
							<template slot="append">
								次
							</template>
						</el-input>
						<span>&nbsp;5 ≤ 次数 ≤ 10000000</span>
					</el-form-item>
				</el-form-item>
			</div>

			<div v-if="editType === 'sendMerchant'">
				<el-form-item label="发放商户" prop="sendMerchant">
					<el-select v-model="form.sendMerchant" placeholder="请选择" class="w-400">
						<el-option :value="1" label="本商户" />
						<el-option :value="2" label="本商户和已合作的所有商户" />
						<el-option :value="3" label="本商户和指定已合作的部分商户" />
					</el-select>
					<el-form-item style="display: inline-block;min-width: 100px" prop="sendMerchantList">
						<el-button v-if="form.sendMerchant === 3" @click="openDialogMerchantsTree('sendMerchant')">
							<span v-if="form.sendMerchantList.length">
								已选择&nbsp;
								<span class="app-text-color-danger">{{ form.sendMerchantList.length }}</span>
								&nbsp;家商户
							</span>
							<span v-else>选择</span>
						</el-button>
					</el-form-item>
				</el-form-item>
			</div>

			<div v-if="editType === 'verifyMerchant' && ['cash', 'discount', 'exchange', 'cash_wx_busi', 'discount_wx_busi'].includes(form.couponType)">
				<!-- 核销商户 -->
				<el-form-item label="核销商户" prop="verifyMerchant">
					<el-select v-model="form.verifyMerchant" @change="changeVerifyMerchant" placeholder="请选择" class="w-400">
						<el-option :value="1" label="本商户所有门店" :disabled="form.couponTag === 1 ? true : false" />
						<el-option :value="4" label="本商户部分门店" :disabled="form.couponTag === 1 ? true : false" />
						<el-option :value="2" label="本商户与所有合作商户" :disabled="form.couponTag === 2 ? true : false" />
						<el-option :value="3" label="本商户与部分合作商户" :disabled="form.couponTag === 2 ? true : false" />
					</el-select>
					<el-form-item style="display: inline-block;min-width: 100px" prop="verifyMerchantList">
						<!-- <el-button v-if="form.verifyMerchant === 3 || form.verifyMerchant === 4" @click="openDialogMerchantsTree('verifyMerchant')">
							<span v-if="form.verifyMerchantList.length">
								已选择&nbsp;
								<span class="app-text-color-danger">{{ form.verifyMerchantList.length }}</span>
								&nbsp;家商户
							</span>
							<span v-else>选择</span>
						</el-button> -->
						<el-button v-if="form.verifyMerchant === 3 || form.verifyMerchant === 4" @click="openDialogMerchantsTree('verifyMerchant')">
							<span v-if="form.verifyMerchantList.length">
								已选择&nbsp;
								<span v-if="form.verifyMerchant != 4" class="app-text-color-danger">{{ form.verifyMerchantList.length }}</span>
								<span v-else class="app-text-color-danger">{{ form.storesNum.length }}</span>
								&nbsp;家{{ form.verifyMerchant == 4 ? '门店' : '商户' }}
							</span>
							<span v-else>选择</span>
						</el-button>
					</el-form-item>
				</el-form-item>
			</div>

			<div v-if="editType === 'verifyMerchant' && ['cash_wx_pay'].includes(form.couponType)">
				<!-- 可核销商户号 -->
				<div>
					<el-form-item label="核销商户" prop="verifyMerchants">
						<el-card :body-style="{ 'padding-bottom': '0px' }" class="nest-card-box">
							<el-input v-model="form.verifyMerchants" :autosize="{ minRows: 3, maxRows: 10 }" type="textarea" />
							<div>一行对应一个商户号(可通过Enter换行)，最多添加50个商户号，包含你自己的商户号</div>
						</el-card>
					</el-form-item>
				</div>
			</div>

			<div v-if="editType === 'verifyBizCode' && ['cash', 'discount', 'exchange', 'cash_wx_busi', 'discount_wx_busi'].includes(form.couponType)">
				<!-- 核销业务 -->
				<el-form-item item label="核销业务" class="is-required">
					<el-select v-model="form.verifyBusinessType" placeholder="请选择" class="w-300">
						<el-option :value="1" label="所有的业务场景下可核销" />
						<el-option :value="2" label="指定部分业务场景下可核销" />
					</el-select>

					<div v-if="form.verifyBusinessType === 2" class="nest-card-box" style="margin-top:10px">
						<el-card :body-style="{ padding: '20px 20px 0 20px' }">
							<el-form-item prop="verifyBusiness">
								<el-checkbox-group v-model="form.verifyBusiness">
									<template v-for="item in manageBizCodeOptions">
										<el-checkbox v-if="(item.usePay && item.canDiscount) || item.key == 9056" :key="item.value" :label="String(item.key)">
											{{ item.label }}
										</el-checkbox>
									</template>
								</el-checkbox-group>
							</el-form-item>
						</el-card>
					</div>
				</el-form-item>
			</div>
		</el-form>

		<DialogMerchantsTree ref="dialogMerchantsTree" />

		<div slot="footer" class="dialog-footer">
			<el-button size="small" round @click="hide">取 消</el-button>
			<el-button size="small" round type="primary" @click="handleSubmit('form')">确 定</el-button>
		</div>
	</el-dialog>
</template>

<script>
import DialogMerchantsTree from '../../components/DialogMerchantsTree';
import CouponValidate from '../../editCoupon/mixin/CouponValidate';
import { mapGetters } from 'vuex';
import { authMerchants } from '../../../api/mch';
import { updateCoupon } from '../../../api/coupon';

export default {
	components: {
		DialogMerchantsTree
	},
	mixins: [CouponValidate],
	data() {
		return {
			// 配置
			couponTypeOptions: {
				cash: '代金券',
				cash_wx_pay: '微信支付代金券',
				cash_wx_busi: '微信商家代金券',
				discount: '折扣券',
				discount_wx_busi: '微信商家折扣券',
				exchange: '兑换券'
			},
			couponTypeGroup: {
				cash: ['cash', 'cash_wx_pay', 'cash_wx_busi'],
				discount: ['discount', 'discount_wx_busi'],
				exchange: ['exchange']
			},
			title: '更新优惠券',
			resolve: null,
			reject: null,
			// 状态
			dialogVisible: false,
			loading: false,
			// 数据
			editType: null,
			form: {
				belongMerchant: null, // 归属商户号
				maxCouponsChecked: true, // 是否勾选  no params
				maxCoupons: null, // 总预算 次数
				maxCouponsByDayChecked: true, // 是否勾选  no params
				maxCouponsByDay: null, // 日总预算 数量
				sendMerchant: 1, // 发券商户类型 1本商户
				sendMerchantList: [],
				verifyMerchant: 1, // 核销商户类型 1本商户  2本商户和所有合作商户 3本商户与合作商户指定门店  4本商户指定店铺
				verifyMerchantList: [],
				verifyMerchants: null, // 微信支付核销商户 需按行转,分割string
				verifyBusinessType: 1, // 业务类型 no params  1：所有 2：部分
				verifyBusiness: [] // 业务类型  需转,分割string
			},
			openForm:''
		};
	},
	computed: {
		...mapGetters(['manageBizCodeOptions'])
	},
	watch: {
		'form.verifyBusinessType'(newVal) {
			if (newVal === 2 && this.form.verifyBusiness && this.form.verifyBusiness.length === 0) {
				this.form.verifyBusiness = ['9000', '9056'];
			}
		}
	},
	beforeCreate() {},
	created() {},
	beforeMount() {},
	mounted() {},
	beforeUpdate() {},
	update() {},
	activated() {},
	deactivated() {},
	beforeDestroy() {},
	destroyed() {},
	methods: {
		// 弹框相关
		open({ editType, form }) {
			console.log(editType);
			this.loading = true;
			
			const params = JSON.parse(JSON.stringify(form));
			this.openForm = params
			this.editType = editType;
			Promise.all([this.getDetail(params), this.getAuthMerchants()]).finally(() => {
				this.show();
				this.loading = false;
			});
			return new Promise((resolve, reject) => {
				this.resolve = resolve;
				this.reject = reject;
			});
		},

		show() {
			this.dialogVisible = true;
		},

		hide() {
			this.resolve = null;
			this.reject = null;
			this.dialogVisible = false;
		},

		close() {
			this.loading = false;
		},

		/**
		 * 数据组
		 */
		// 获取详情
		getDetail(params) {
			return new Promise(resolve => {
				// 发放商户
				switch (params.sendMerchant) {
					case 1:
					case 2:
						params.sendMerchantList = [];
						break;
					case 3:
						params.sendMerchantList.forEach(v => {
							v.merchant = 'M-' + v.merchant;
							v.shop = v.shop ? v.shop.split(',') : [];
						});
						break;
				}

				if (['cash', 'discount', 'exchange', 'cash_wx_busi', 'discount_wx_busi'].includes(params.couponType)) {
					// 核销商户
					switch (params.verifyMerchant) {
						case 1:
						case 2:
							params.verifyMerchantList = [];
							break;
						case 3:
							params.verifyMerchantList.forEach(v => {
								v.merchant = 'M-' + v.merchant;
								v.shop = v.shop ? v.shop.split(',') : [];
							});
							break;
						case 4:
							params.storesNum = params.verifyMerchantList[0].shop.split(',');
							break;
					}
					// 核销业务
					if (params.verifyBusiness) {
						params.verifyBusiness = params.verifyBusiness.split(',');
						params.verifyBusinessType = 2;
					} else {
						params.verifyBusinessType = 1;
						params.verifyBusiness = [];
					}
				} else {
					params.verifyBusinessType = 1;
					params.verifyBusiness = [];
				}
				// 格式化微信代金券 专用
				if (['cash_wx_pay'].includes(params.couponType)) {
					// 核券商户号
					params.verifyMerchants = params.verifyMerchants.replace(/,/g, '/n');
					if (params.wxPayType) {
						params.wxPayTypeType = 1;
						params.wxPayType = params.wxPayType.split(',');
					} else {
						params.wxPayTypeType = 2;
						params.wxPayType = [];
					}
				} else {
					params.wxPayTypeType = 1;
					params.wxPayType = [];
				}

				// 格式化预算
				params.maxCouponsChecked = true;
				params.maxCouponsByDayChecked = true;
				if (['cash', 'discount', 'exchange'].includes(params.couponType)) {
					params.maxCouponsChecked = !!params.maxCoupons;
					params.maxCouponsByDayChecked = !!params.maxCouponsByDay;
				}
				console.log('格式化完成', params);
				this.form = params;
				resolve();
			});
		},

		// 获取合作商户
		getAuthMerchants() {
			let params = this.openForm
			return new Promise(resolve => {
				if (params.belongMerchant) {
					authMerchants({ belongMerchant: params.belongMerchant, queryType: params.queryType })
						.then(res => {
							const allMchList = [];
							res.data.forEach(v => {
								v.id = 'M-' + v.id;
								allMchList.push({
									id: v.id,
									name: v.name,
									shops: []
								});
							});
							this.allMchList = allMchList;
							this.allMchShopList = res.data;
							this.form.storesMaxNum = res.data[0].shops.length;
						})
						.finally(() => {
							resolve();
						});
				} else {
					resolve();
				}
			});
		},

		// 打开商户
		openDialogMerchantsTree(mode) {
			let checkedIds = [];
			let treeData = [];
			let verifyMerchant = this.form.verifyMerchant;
			if (mode === 'sendMerchant') {
				treeData = this.allMchList;
				this.form.sendMerchantList.forEach(v => {
					checkedIds.push(v.merchant);
				});
			} else if (mode === 'verifyMerchant') {
				treeData = this.allMchShopList;
				if (this.form.verifyMerchantList.length > 0) {
					let shop = this.form.verifyMerchantList[0].shop;
					if (typeof shop == 'string') {
						this.form.verifyMerchantList[0].shop = this.form.verifyMerchantList[0].shop.split(',');
					}
				}
				this.form.verifyMerchantList.forEach(v => {
					checkedIds = checkedIds.concat(v.shop);
				});
			}
			this.$refs.dialogMerchantsTree.open({ treeData, checkedIds, verifyMerchant }).then(res => {
				console.log('选择商户', res);
				if (mode === 'sendMerchant') {
					this.$refs.form.clearValidate(['sendMerchantList']);
					this.form.sendMerchantList = res;
				} else if (mode === 'verifyMerchant') {
					this.$refs.form.clearValidate(['verifyMerchantList']);
					this.form.verifyMerchantList = res;

					// 选中所有门店，自动切换为“本商户所有门店”，否则设置 storesNum
					let arr = [];
					let data = this.form.verifyMerchantList;
					let shopLen = data[0].shop.length;
					if (this.form.verifyMerchant == 4 && shopLen < this.form.storesMaxNum) {
						if (shopLen > 0) {
							this.form.storesNum = data[0].shop;
						}
					} else {
						data.forEach(el => {
							if (el.inviteCooperateVo) {
								arr.push(el);
							}
						});
						if (arr.length <= 0) {
							this.form.verifyMerchant = 1;
							this.form.capValue == '';
						}
					}
				}
			});
		},
		changeVerifyMerchant(e){
			if(e === 3){
				this.form.queryType = 0
			}
			this.getAuthMerchants()
		},

		handleSubmit() {
			console.log(this.form);
			this.$refs.form.validate(valid => {
				if (valid) {
					const params = JSON.parse(JSON.stringify(this.form));
					// 根据类型更新不同信息
					const submitForm = {};
					submitForm.id = params.id;
					switch (this.editType) {
						case 'maxCoupons':
							submitForm.maxCoupons = params.maxCoupons;
							break;
						case 'maxCouponsByDay':
							submitForm.maxCouponsByDay = params.maxCouponsByDay;
							break;
						case 'sendMerchant':
							// 发放商户
							switch (params.sendMerchant) {
								case 1:
								case 2:
									params.sendMerchantList = [];
									break;
								case 3:
									params.sendMerchantList.forEach(v => {
										v.merchant = String(v.merchant).replace('M-', '');
										v.shop = v.shop.join();
									});
									break;
							}
							submitForm.sendMerchant = params.sendMerchant;
							submitForm.sendMerchantList = params.sendMerchantList;
							break;
						case 'verifyMerchant':
							if (['cash', 'discount', 'exchange', 'cash_wx_busi', 'discount_wx_busi'].includes(params.couponType)) {
								// 核销商户
								switch (params.verifyMerchant) {
									case 1:
									case 2:
										params.verifyMerchantList = [];
										break;
									case 3:
										params.verifyMerchantList.forEach(v => {
											v.merchant = String(v.merchant).replace('M-', '');
											v.shop = v.shop.join();
										});
										break;
									case 4:
										params.verifyMerchantList.forEach(v => {
											v.merchant = String(v.merchant).replace('M-', '');
											v.shop = v.shop.join();
										});
										break;
								}
								submitForm.verifyMerchant = params.verifyMerchant;
								submitForm.verifyMerchantList = params.verifyMerchantList;
							} else if (['cash_wx_pay'].includes(params.couponType)) {
								// 核券商户号
								params.verifyMerchants = params.verifyMerchants
									.trim()
									.replace(/\r\n|\n|\r/g, ',')
									.replace(/,+/g, ',');
								submitForm.verifyMerchants = params.verifyMerchants;
							}
							break;
						case 'verifyBizCode':
							// 核销业务
							params.verifyBusiness = params.verifyBusinessType === 1 ? '' : params.verifyBusiness.join();
							submitForm.verifyBusiness = params.verifyBusiness;
							break;
					}

					this.loading = true;
					updateCoupon(submitForm)
						.then(res => {
							this.$notify({
								title: '成功',
								message: '更新成功',
								type: 'success',
								duration: 2000,
								offset: 40
							});
							this.resolve && this.resolve();
							this.hide();
						})
						.finally(() => {
							this.loading = false;
						});
					console.log(submitForm);
				}
			});
		}
		/**
		 * 按钮组
		 */
		/**
		 * 状态组
		 */
		/**
		 * 方法组
		 */
	}
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.w-200 {
	width: 200px;
}
.w-300 {
	width: 300px;
}

.w-400 {
	width: 400px;
}
</style>
